import { computed, ref } from 'vue'
import { tou } from 'pinyin/data/dict-zi-web'

export default function useShortcut(props, groupRef) {
  const ANCHOR_HEIGHT = 18
  const scrollRef = ref(null)

  const shortcutList = computed(() => {
    return props.data.map(group => group.title)
  })

  const touch = {}

  function onShortcutClick(e) {
    const anchorIndex = parseInt(e.target.dataset.index)
    touch.y1 = e.pageY
    touch.anchorIndex = anchorIndex

    scrollTo(anchorIndex)
  }

  function onShortcutTouchStart(e) {
    const anchorIndex = parseInt(e.target.dataset.index)
    touch.y1 = e.touches[0].pageY
    touch.anchorIndex = anchorIndex

    scrollTo(anchorIndex)
  }
  function onShortcutTouchMove(e) {
    touch.y2 = e.touches[0].pageY
    const delta = (touch.y2 - touch.y1) / ANCHOR_HEIGHT | 0 // |0 向下取整
    const anchorIndex = touch.anchorIndex + delta
    scrollTo(anchorIndex)
  }
  function onShortcutTouchEnd(e) {}

  function scrollTo(index) {
    if (isNaN(index)) {
      return
    }
    index = Math.max(Math.min(shortcutList.value.length - 1, index), 0) // index区间在shortcutList长度减1 和 0 之间
    const targetEl = groupRef.value.children[index]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEl, 0)
  }
  return {
    shortcutList,
    onShortcutClick,
    onShortcutTouchStart,
    onShortcutTouchMove,
    onShortcutTouchEnd,
    scrollRef
  }
}
